package com.system.Tools;

import com.system.function.object.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Component
public class FileTool {
    @Autowired
    private TimeTools timeTools;

    public Boolean upload(MultipartFile file, Supplier Supplier) {
        try {
            if (file.isEmpty()) {
                return false;
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));

            Long timestamp = timeTools.getTimestamp();
            // 设置文件存储路径
            String filePath = "D://file//";
            String path = filePath + timestamp + fileName + suffixName;
            Supplier.setImgPath(timestamp + fileName + suffixName);

            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            return true;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
